package com.alpha.components;

import com.alpha.common.utils.BusinessException;
import com.alpha.common.utils.SecurityUtil;
import com.alpha.module.user.dao.AccountMapper;
import com.alpha.module.user.entity.Account;
import org.springframework.stereotype.Service;

/**
 * 账户资金服务
 * @author zhaojiulin
 * @DATE 2020/2/27 13:34
 */
@Service(value = "accountFundsService")
public class AccountFundsService {
    private final AccountMapper accountMapper;

    public AccountFundsService(AccountMapper accountMapper) {
        this.accountMapper = accountMapper;
    }

    /**
     * 检查账户资金
     * 是否被篡改是否安全
     * @param id
     * @return
     * @throws BusinessException
     */
    public Boolean checkAccount(long id) throws BusinessException {
        // Object key = this.systemSetService.getParamVal(Enums.Params.Key.getKey());
        Object key = "@#$%!1234";
        if (key == null) {
            throw new BusinessException("请求异常");
        }
        Account account = this.accountMapper.selectByPrimaryKey(id);
        String sign = SecurityUtil.MD5(account.getId()
                + account.getBalance().toString()
                + account.getTotalAmount().toString()
                + account.getBalance().toString()
                + key.toString());
        return sign.equals(account.getVersion());
    }

    /**
     * 修改/创建加密资金安全字符串
     * @param accountId
     * @throws BusinessException
     */
    public void encryptAccount(long accountId) throws BusinessException {
        Object key = "@#$%!1234";
        if (key == null) {
            throw new BusinessException("请求异常");
        }
        Account account = this.accountMapper.selectByPrimaryKey(accountId);
        String sign = SecurityUtil.MD5(account.getId()
                + account.getBalance().toString()
                + account.getTotalAmount().toString()
                + account.getBalance().toString()
                + key.toString());
        Account acc = new Account();
        acc.setId(accountId);
        acc.setVersion(sign);
        this.accountMapper.updateByPrimaryKeySelective(acc);
    }

}
